<?php
declare (strict_types=1);

namespace app\command;

use app\common\business\Contract;
use app\common\business\DiseasePath;
use app\common\business\Message;
use app\common\lib\Redis;
use app\common\lib\ZhyxBeanstalkd;
use app\common\lib\ZhyxMongo;
use app\common\model\BaseModel;
use app\common\model\BindDiseasePath;
use app\common\model\CollectCase;
use app\common\model\CollectClass;
use app\common\model\DiseasePatientTask;
use app\common\model\DiseasePatientTaskDetail;
use app\common\model\PacketConfig;
use app\common\model\TimingTask;
use app\impl\SimpleFactory;
use catchAdmin\propaganda\service\EdCenterService;
use catchAdmin\registration\service\TaskService;
use MongoDB\BSON\ObjectId;
use Pheanstalk\Exception\ClientException;
use Pheanstalk\Exception\ConnectionException;
use Pheanstalk\Exception\ServerException;
use think\console\Command;
use think\console\Input;
use think\console\input\Argument;
use think\console\input\Option;
use think\console\Output;
use think\Exception;
use think\facade\Log;

class AutoRunRules extends Command
{


    protected function configure(): void
    {
        // 指令配置
        $this->setName('autoRunRules')
            ->setDescription('自动分组');
    }

    /**
     * @throws \Exception
     */
    protected function execute(Input $input, Output $output)
    {
        $data = $this->getSourceData();

        if (!empty($data)) {
            foreach ($data as $k => $v) {
                $this->runContent((array)$v);
            }
        }

    }


    /**
     * 获取数据源
     * @return array
     */
    private function getSourceData(): array
    {
        $date = "2024-10-22";
        $collection = (ZhyxMongo::getInstance())->setCollection('disease_patient_task_detail');
        $cursor = $collection->aggregate([['$match' => ['task_start_date' => $date, 'latest_status' => 0]], ['$sort' => ['bind_main_id' => 1, 'step_order' => 1]]]);

        return iterator_to_array($cursor);
    }

    private function runContent($data)
    {
        try {
            $date = "2024-10-22";
            $result = [];
            switch ($data["task_type"]) {
                case "plan":
                case "others":
                    $taskType = $data["task_type"] === "others" ? 4 : 5;
                    $result = (new  Message())->saveMessage($taskType, (string)$data['task_id'], $data["task_name"], $data["patient_id"], $data["patient_name"] ?? "患者");
                    break;
                case "content":
                    $result = (new EdCenterService())->automaticPushEd($data["patient_id"], $data["attachment_parent_value"], $data["attachment_value"], "1");
                    break;
                case "form":
                    $result = (new TaskService())->automaticPushFollow($data["patient_id"], $data["attachment_value"], 0, 1);
                    break;

            }

            if ($result) {
                $outerId = $result["history_id"] ?? "";
                # 将本条任务更新为进行中

                $modifyDetailStatus = (new DiseasePatientTaskDetail())->where([["id", "=", (string)$data["_id"]]])->update([
                    'latest_status' => 2,
                    'outer_id' => $outerId,
                    'creator_by' => '系统',
                ]);
                $collection = ZhyxMongo::getInstance()->setCollection('disease_patient_task');
                // 定义查询条件
                $filter = [
                    '$and' => [
                        ['planList.plan_task_id' => $data["task_id"]],
                        ['deleted_at' => 0]
                    ]
                ];
// 定义更新操作
                $update = [
                    '$set' => [
                        'planList.$[elem].plan_task_status' => 2,
                        'planList.$[elem].complete_date' => $date,
                        'plan_status' => 1
                    ]
                ];
// 定义数组过滤器
                $options = [
                    'arrayFilters' => [['elem.plan_task_id' => $data["task_id"]]]
                ];
                $result = $collection->updateOne($filter, $update, $options);

                (new BindDiseasePath())->where([["id", "=", $data["bind_main_id"]]])->update([
                    'step' => $data["step_order"],
                    'latest_status' => "1"
                ]);
            }
        } catch (\Exception $exception) {
            Log::error("推送失败,失败原因:" . $exception->getMessage());
        }

    }


}